package server.connector;

import server.connector.http.HttpResponseImpl;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import java.io.IOException;
import java.io.OutputStream;
/*
封装输出流,至多写length个字节,当length < 0,无限制
当流已将关闭时,再关闭会抛出IOException异常
 */
/*
2023/1/26 该类内容全部写完,后续直接使用,无需修改
by cyl
 */
public class ResponseStream extends ServletOutputStream {

    protected HttpResponseImpl response = null;
    protected OutputStream stream = null;
    protected boolean closed = false;
    protected boolean commit = false;
    protected int length = -1;
    protected int count = 0;
    protected boolean suspended = false;

    public ResponseStream(HttpResponseImpl response) {
        closed = false;
        commit = false;
        count = 0;
        this.response = response;
        this.stream = response.getStream();
        this.suspended = response.isSuspended();
    }

    @Override
    public void close() throws IOException {
        if (suspended || closed)
            throw new IOException("流已被关闭");
        response.flushBuffer();
        closed = true;
    }

    @Override
    public void flush() throws IOException {
        if (suspended || closed)
            throw new IOException("流已被关闭");
        if (commit)
            response.flushBuffer();
    }

    @Override
    public void write(int b) throws IOException {
        if (suspended)
            return;
        if (closed)
            throw new IOException("流已被关闭");
        if (length > 0 && count >= length) {
            throw new IOException("无法写超过Content-length数的字节");
        }
        response.write(b);
        count++;
    }

    @Override
    public void write(byte[] b) throws IOException {
        write(b, 0, b.length);
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        if (suspended)
            return;
        if (closed)
            throw new IOException("流已被关闭");
        int wLen = len;
        if (length > 0 && (count + len) > length) {
            wLen = length - count;
        }
        response.write(b, off, wLen);
        count += wLen;
        if (wLen < len) {
            throw new IOException("无法写超过Content-length数的字节");
        }
    }
    public void reset() {
        count = 0;
    }
    //getter
    public boolean getCommit() {
        return this.commit;
    }
    public boolean isSuspended() {
        return this.suspended;
    }
    public boolean isClosed() {
        return this.closed;
    }

    //setter
    public void setCommit(boolean commit) {
        this.commit = commit;
    }
    public void setSuspended(boolean suspended) {
        this.suspended = suspended;
    }


    //暂不实现------------------------------------------------------------------------------
    @Override
    public boolean isReady() {
        return false;
    }

    @Override
    public void setWriteListener(WriteListener writeListener) {

    }


}
